package com.sharemarking.application.common.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sharemarking.application.common.BaseSpecification;
import com.sharemarking.application.common.entity.Employee;
import com.sharemarking.application.common.entity.Share;
import com.sharemarking.application.common.repository.EmployeeRepo;
import com.sharemarking.application.common.repository.ShareRepo;

@Controller
@RequestMapping("share")
public class ShareController {
	
	@Autowired
	private ShareRepo dao;

	@Autowired
	private EmployeeRepo er;

	/**
	 * 图文信息数据列表展示
	 * 
	 * @param e
	 * @param page
	 * @param size
	 * @param model
	 */
	@GetMapping(value ="index")
	@PreAuthorize("hasPermission('sys:share',1)")
	public void index(Share e, Integer page, Integer size, Model model) {
		if (page == null)
			page = 0;
		else
			page -= 1;
		if (size == null)
			size = 10;
		Sort order = new Sort(Direction.DESC, "id");
		PageRequest req = new PageRequest(page, size, order);
		Page<Share> p = dao.findAll(new BaseSpecification<Share>(e), req);
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/share/";
		model.addAttribute("pro", pro);
		model.addAttribute("page", p);
		model.addAttribute("search", e);
	}

	/**
	 * 获取实体接口
	 * 
	 * @param e
	 * @return
	 */
	@GetMapping(value="{id}")
	@PreAuthorize("hasPermission('sys:share',1)")
	public String get(Share obj, Model model) {
		if (obj.getId() != 0)
			obj = dao.findOne(obj.getId());
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/share/";
		model.addAttribute("pro", pro);
		model.addAttribute("obj", obj);
		return "share/form";
	}
	
	/**
	 * id==0 => 新增实体 id!=0 => 更新实体
	 * 
	 * @param e
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value="{id}")
	@Transactional
	@PreAuthorize("hasPermission('sys:share',#target.id==0?8:4)")
	public String post(Share target, Model model, @RequestParam("PICN")  MultipartFile PICN, HttpServletRequest request)
			throws IOException {

		if (!PICN.isEmpty()) {
			// 文件上传
//			String PICName = null;
			
			MultipartFile file = PICN;
//			PICName = file.getOriginalFilename();
			// 把要上传的图片转换成流
			InputStream isRef = file.getInputStream();
 
			// 获取classes下的路径
//			String path = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/share/";
			String targetDir1 = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/share";
			File file1 = new File(targetDir1);
			file1.mkdirs();
			
			// 图片命名为loginName+Data+8位随机数.png
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式

			String Date = dateFormat.format(now);
			StringBuilder str = new StringBuilder();// 定义变长字符串

			// 随机生成数字，并添加到字符串
			Random random = new Random();
			for (int i = 0; i < 8; i++) {
				str.append(random.nextInt(10));
			}

//			String path2 = path + Date + str.toString() + ".png";
			String path3 = Date + str.toString() + ".png";
			
			File targetFile = new File(targetDir1, path3);
			// 通过输出流将图片写入到相应的地方
			FileOutputStream fosRef = new FileOutputStream(targetFile);
			IOUtils.copy(isRef, fosRef);
			
			// 添加
			if (target.getId() == 0) {

				// 关联关系
				Integer employeeId = Integer.parseInt(request.getParameter("employeeId"));
				
				Employee e = er.findOne(employeeId);
				target.setEmployee(e);
				
				// 将接收的文件保存到指定文件中
				target.setPhoto(path3);
				// 保存图片路径
			//	target.setImgUrl(targetDir1 + "/" + PICName);
				PICN.transferTo(targetFile);
				
				dao.save(target);
				return "redirect:index";
			} else {
				// 编辑
				Share share = dao.findOne(target.getId());
				if (share == null)
					return null;

				// 关联关系
				Integer employeeId = Integer.parseInt(request.getParameter("employeeId"));
				System.out.println("employeeId:"+employeeId);
				Employee e = er.findOne(employeeId);
				
				// 将接收的文件保存到指定文件中
				PICN.transferTo(targetFile);
				share.setDescribe1(target.getDescribe1());
				share.setEmployee(e);
				share.setShareTime(target.getShareTime());
				share.setPhoto(path3);

			}
		}else{
			// 编辑
			Share share = dao.findOne(target.getId());
			if (share == null)
				return null;

			// 关联关系
			Integer employeeId = Integer.parseInt(request.getParameter("employeeId"));
			System.out.println("employeeId:"+employeeId);
			Employee e = er.findOne(employeeId);
			
			share.setDescribe1(target.getDescribe1());
			share.setEmployee(e);
			share.setShareTime(target.getShareTime());
			
			return "redirect:index";
			 
		}
		return "redirect:index";
	}
	

	/**
	 * 逻辑删除
	 * 
	 * @param id
	 */
	@RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
	@Transactional
	public String delete(@PathVariable("id") Integer id) {
		dao.findOne(id).setDelFlag(true);
		return "redirect:../index";
	}

}
